using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Xml;

namespace Dimok.Web {

	////////////////////////////////////////////////////////////////////////////////////////////////////
	/// <summary>	Http. </summary>
	///
	/// <remarks>	Dimon, 12/21/2010. </remarks>
	////////////////////////////////////////////////////////////////////////////////////////////////////

	partial class HTTP {

		////////////////////////////////////////////////////////////////////////////////////////////////////
		/// <summary>	Ca. </summary>
		///
		/// <remarks>	Dimon, 12/21/2010. </remarks>
		////////////////////////////////////////////////////////////////////////////////////////////////////

		public class CA {

			////////////////////////////////////////////////////////////////////////////////////////////////////
			/// <summary>	Gets a web request. </summary>
			///
			/// <remarks>	Dimon, 12/21/2010. </remarks>
			///
			/// <param name="url">	URL of the document. </param>
			///
			/// <returns>	The web request. </returns>
			////////////////////////////////////////////////////////////////////////////////////////////////////

			private static HttpWebRequest GetWebRequest(string url) {
				HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
				req.Accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-powerpoint, application/vnd.ms-excel, application/msword, */*";
				req.Headers.Add("Accept-Language", "en - us");
				req.Headers.Add("Accept-Encoding", "gzip, deflate");
				req.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)";
				return req;
			}

			////////////////////////////////////////////////////////////////////////////////////////////////////
			/// <summary>	Street by zip. </summary>
			///
			/// <remarks>	Dimon, 12/21/2010. </remarks>
			///
			/// <param name="zip">	The zip. </param>
			///
			/// <returns>	. </returns>
			////////////////////////////////////////////////////////////////////////////////////////////////////

			public static PostalDS StreetByZip(string zip) {
				PostalDS dsPostal = new PostalDS();
				PostalDS.StreetDataTable dtStreets = dsPostal.Street;
				zip = CheckZipType(zip,ZipType.CA);
				if (zip == "") return dsPostal;
				string searchUrl = "http://www.canadapost.ca/tools/pcl/bin/cp_search_response-e.asp";
				string data = "app_language=english&app_response_start_row_number=1&app_response_rows_max=9&app_source=range&query_source=a&app_state=production&Name=&street_number=&Suffix=NULL&unit_number=&street_name=&street_type=&street_direction=&postal_code2=" + zip + "&postal_code=" + zip + "&city=&prov=&delivery_number=&Submit.x=33&Submit.y=10";
				HttpWebRequest req = GetWebRequest(searchUrl);
				byte[] dataBytes = new ASCIIEncoding().GetBytes(data);
				req.Method = "POST";
				req.ContentType = "application/x-www-form-urlencoded";
				req.ContentLength = dataBytes.Length;
				Stream reqStream = req.GetRequestStream();
				reqStream.Write(dataBytes, 0, dataBytes.Length);
				reqStream.Close();
				HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
				string charSet = resp.CharacterSet;
				string response = new StreamReader(resp.GetResponseStream(), Encoding.GetEncoding(charSet)).ReadToEnd();
				resp.Close();
				string regExString = "<table.+?class=\"postalCode\".*?>[\\s\\S]+?</table>";
				Match m = Regex.Match(response, regExString);
				string xmlString = Regex.Replace(Regex.Replace(m.Value.Replace("<br>", ""), "<img[^>]*>", ""), @"<(\w+)\s[^>]+?>", "<$1>");
				if (xmlString != "") {
					XmlDocument doc = new XmlDocument();
					doc.LoadXml(xmlString);
					XmlNodeList nodes = doc.SelectNodes("*/tr");
					if (nodes.Count > 0) {
						nodes[0].ParentNode.RemoveChild(nodes[0]);
						nodes = doc.SelectNodes("*/tr");
					}
					foreach (XmlElement node in nodes) {
						int l = node.ChildNodes.Count - 1;
						dtStreets.AddStreetRow("","","",node.ChildNodes[l - 6].InnerText.Trim(), node.ChildNodes[l - 4].InnerText, node.ChildNodes[l - 2].InnerText, node.ChildNodes[l - 1].InnerText, node.ChildNodes[l].InnerText,"CA");
						if( dsPostal.City.Count == 0)
							dsPostal.City.AddCityRow(node.ChildNodes[l - 2].InnerText, node.ChildNodes[l - 1].InnerText,"CA");
					}
				}
				return dsPostal;
			}
		}
	}
}
